import json
import xml.etree.ElementTree as ET
import copy

'''
{
    "_id" : ObjectId("5af3a85f89fa21203f2eb533"),1
    "noNamespaceSchemaLocation" : "unitData-1.0.xsd",
    "unit" : "NO_CODE",(代码)
    "equipment" : "R015D-15E0235",
    "starttime" : "2018-03-26T10:29:41+08:00",
    "endtime" : "2018-03-26T10:38:25+08:00",
    "state" : "nok",
    "firstTime" : "2018-03-26 10:29:41",
    "timeStamp" : "2016.12.20 10:10:57",
    "userName" : "s",
    "track" : "1",
    "pcbNo" : "18212",
    "weldingProgram" : "15S-T2-HH-003.xml",
    "programLibrary" : "15S-T2-HH",
    "productName" : "kein_Product_Code",
    "code" : "NO_CODE",
    "pattern" : "0",
    "alarm" : "1",
    "pcbLength" : "26.4",
    "coolingBlowerSwitch" : "ON",
    "nitrogenSwitch" : "ON",
    "epcFile" : "no_epc_file",
    "epcTimeStamp" : "000-00-00 00:00:00",
    "equipment" : "处理时间",
    "UnitOfMeasure" : "s",
    "value" : "524",
    "time" : "2018-03-26T10:29:41+08:00"
}

'''

_PARMDICT = {
    "时间": 'firstTime',
    '时间戳 焊接程 式': 'timeStamp',
    '用户名': 'userName',
    '追踪': 'track',
    '板子号码': 'pcbNo',
    '焊接程 式': 'weldingProgram',
    '程序库': 'programLibrary',
    '产品名称': 'productName',
    '代码': 'code',
    '模式': 'pattern',
    '报警': 'alarm',
    'PCB长度（mm）': 'pcbLength',
    '冷却吹风开关': 'coolingBlowerSwitch',
    '氮气开关': 'nitrogenSwitch',
    'EPC 文件': 'epcFile',
    'EPC 时间戳': 'epcTimeStamp',

}


def anlizexml(filepath):
    result = []
    dict = {}
    tree = ET.parse(filepath)
    root = tree.getroot()
    rootattr = root.attrib
    dict['noNamespaceSchemaLocation'] = rootattr.get(
        '{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation')
    dict['unit'] = rootattr.get('unit')
    dict['equipment'] = rootattr.get('equipment')
    dict['starttime'] = rootattr.get('starttime')
    dict['endtime'] = rootattr.get('endtime')
    dict['state'] = rootattr.get('state')
    for parameter in root.findall('*/parameter'):
        temparrt = parameter.attrib
        name = temparrt.get('name')
        dict[_PARMDICT.get(name)] = temparrt.get('value')

    for channel in root.findall('*/channel'):
        tempdict=copy.copy(dict)
        tempattr=channel.attrib
        tempdict['equipment']= tempattr.get('name')
        tempdict['UnitOfMeasure']= tempattr.get('UnitOfMeasure')
        for child in channel:
            tag=child.tag
            if tag=='sample':
                childattr=child.attrib
                tempdict['value']= childattr.get('value')
                tempdict['time']= childattr.get('time')
            elif tag=='nominalValue':
                childattr=child.attrib
                tempdict['nominalValue']= childattr.get('value')
        result.append(tempdict)
    return result

if __name__ == '__main__':
    anlizexml('/home/naiqizhang/桌面/Protocol/2018/03/26/XML/20180326_103423.xml')
